/**
* Created by zy on 20210908
*/
$(function () {
    // 页面初始化
    const USERID = Util.getUserId(), USERNAME = Util.getUserName();
    // 列表传参
    var QueryJson = {
    };
    //下拉框方法
    Util.InitDroupDownDom();
    //获取列表数据
    InitDataFn();
    //查询按钮的点击
    $(".period").on("click", function () {
        SearchListFn();
    });
    function SearchListFn() {
        Util.ShowLoadingBox();
        setTimeout(() => {
            InitDataFn();
        }, 1000);
    }

    //初始化或查询时请求数据
    function InitDataFn(data) {
        // 显示数据
        Util.ShowListBox();

    }

    // 编辑操作
    $("#tree_map").on("click",".tree_item_edit_add",function(e){
        if( $(this).parents(".tree_sub").length > 0 ){
            let curModal = $(this).parents(".tree_sub_top").find(".tree_sub_edit_modal")
            curModal.show();
        }
    })
    $("#tree_map").on("mouseleave",".tree_sub_edit_modal",function(e){
        $(this).hide();
    })
    // tools 操作按钮
    $(".tree_tools").on("click", "li", function () {
        let liId = $(this).attr("id")
        let curSize = Number($("html").css("fontSize").replace("px",""))
        // 放大
        if (liId === "tree_enlarge") {
            $("html").css("fontSize",curSize+10)
        }
        // 缩小
        if (liId === "tree_narrow") {
            $("html").css("fontSize",curSize-10)
        }
        console.log($("html").css("fontSize"))

        // 全屏
        if (liId === "tree_fullScreen") {
        }
        // 编辑
        if (liId === "tree_edit") {
            if( $(".tree_edit_item").hasClass("hide_edit") ){
                // 显示编辑按钮,隐藏拜访数目,子机构名称最大显示数目变少
                $(".tree_edit_item").removeClass("hide_edit")
            }else{
                // 隐藏编辑按钮,显示拜访数目,子机构名称最大显示数目变多
                $(".tree_edit_item").addClass("hide_edit")
            }
        }
        // 导出图片
        if (liId === "tree_save") {
            exportPng();
        }

        // 重新画线
        drawLine()
    });
    // 导出图片
    function exportPng() {
        var DomeW = $("#tree_map")[0].offsetWidth;//获取目标元素的宽高
        var DemoH = $("#tree_map")[0].offsetHeight;//获取目标元素的宽高
        html2canvas(document.querySelector("#tree_map"), {
            useCORS: true,
            width: DomeW,
            height: DemoH
        }).then(function (canvas) {
            var imgUri = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 获取生成的图片的url base64
            Util.Download({
                fileName: "组织结构树.png",// 文件名称
                base64: imgUri
            })
        })
    }
    // 渲染数据
    $("#tree_map_content").html(getTreeHtml(data1.data));

    // 画线
    drawLine()
    function drawLine(){
        clearLine()
        let t1 = setTimeout(function(){
            setLine()
        },216)
    }
    // 描点连线
    function setLine(){
        // 设置链接点
        $(".tree_assembly").append(`<p class="tree_line_dot dot_top"></p><p class="tree_line_dot dot_bottom"></p>`)
        $(".dot_top").eq(0).remove()
        $(".dot_bottom").eq($(".dot_bottom").length-1).remove()
        // 自动创建svg
        var container = document.getElementById("tree_map");
        var svgcontainer = document.getElementById("svgcontainer");
        let svgcontainerLeft = svgcontainer.getBoundingClientRect().left
        let svgcontainerTop = svgcontainer.getBoundingClientRect().top
        var svgns = "http://www.w3.org/2000/svg";
        var svger = document.createElementNS(svgns, "svg");
        svger.setAttribute("width", container.clientWidth);
        svger.setAttribute("height", container.clientHeight);
        svger.setAttribute("viewBox", "0 0 " + container.clientWidth + " " + container.clientHeight);
        svgcontainer.appendChild(svger);
        // 画线 点相连
        dotEach($("#tree_map_content"))
        function dotEach(Parent){
            Parent.children(".tree_layer:not(.tree_layer_line)").each(function (i, item) {
                if($(item).next().hasClass("tree_layer_line")){
                    // 分叉节点 
                    let curBottomDot = null;
                    if($(item).find(".dot_bottom").length > 0){
                        // 这一层的最后一个节点
                        curBottomDot = $(item).find(".dot_bottom:last")
                    }
                    if(curBottomDot && $(item).next().children(".tree_layer").length > 0){
                        $(item).next().children(".tree_layer").each((layerIdx,layerItm)=>{
                            console.log(curBottomDot, layerItm)
                            if( $(layerItm).children(".ownerContactList").length > 0 ){
                                $(layerItm).children(".ownerContactList").each((i,dd)=>{
                                    // 多个负责人
                                    $(dd).find(".dot_top").each((ownerLayerIdx,DotTopItm)=>{
                                        linedot($(curBottomDot), $(DotTopItm),1);
                                    })
                                    linedot(curBottomDot, $(layerItm).find(".dot_top:first"),1);
                                })
                            }else{
                                linedot(curBottomDot, $(layerItm).find(".dot_top:first"),1);
                            }
                        })
                    }else if(curBottomDot && $(item).next().children(".tree_layer_line").length > 0){
                        console.log(curBottomDot)
                        // 子机构负责人和子机构相连
                        $(item).next().children(".tree_layer_line").each((cLayerLineIdx,cLayerLineItm)=>{
                            // 子机构负责人和子机构相连
                            if($(item).hasClass("ownerContactList")){
                                // 多个负责人
                                $(item).find(".dot_bottom").each((ownerLayerIdx,DotBottomItm)=>{
                                    linedot($(DotBottomItm), $(cLayerLineItm).find(".dot_top:first"),1);
                                })
                            }else{
                                // 单个负责人
                                linedot(curBottomDot, $(cLayerLineItm).find(".dot_top:first"),1);
                            }
                            dotEach($(cLayerLineItm))
                        })
                    }
                    // 下一层负责人+子机构
                    if($(item).next().children(".tree_layer").length > 0){
                        $(item).next().children(".tree_layer").each((cLayerIdx,cLayerItm)=>{
                            dotEach($(cLayerItm))
                        })
                    }
                }else{
                    // 上一层:联系人 下一层：有负责人的联系人 相连
                    if ($(item).find(".dot_bottom").length > 0 &&
                        Parent.children(".tree_layer:not(.tree_layer_line)").eq(i+1).length > 0 &&
                        Parent.children(".tree_layer:not(.tree_layer_line)").eq(i+1).find(".dot_top").length>0) 
                    {
                        linedot($(item).find(".dot_bottom:last"), Parent.children(".tree_layer:not(.tree_layer_line)").eq(i+1).find(".dot_top").eq(0),2);
                    }
                }
            })
        }
        $("#tree_map_content").children(".tree_layer:not(.tree_layer_line)").each(function (i, item) {
            if($(item).next().hasClass("tree_layer_line")){
                // 分叉节点 
                let curBottomDot = null;
                if($(item).find(".dot_bottom").length > 0){
                    curBottomDot = $(item).find(".dot_bottom:last")
                }
                if(curBottomDot && $(item).next().children(".tree_layer").length > 0){
                    $(item).next().children(".tree_layer").each((layerIdx,layerItm)=>{
                        linedot($(item).find(".dot_bottom:last"), $(layerItm).find(".dot_top:first"),1);
                    })
                }
            }else{
                if ($(item).find(".dot_bottom").length > 0 &&
                    $("#tree_map_content .tree_layer:not(.tree_layer_line)").eq(i+1).length > 0 &&
                    $("#tree_map_content .tree_layer:not(.tree_layer_line)").eq(i+1).find(".dot_top").length>0) {
                    linedot($(item).find(".dot_bottom:last"), $("#tree_map_content .tree_layer:not(.tree_layer_line)").eq(i+1).find(".dot_top").eq(0),2);
                }
            }
        })
        //连接点
        var timepath;
        function linedot(s, e,tt) {
            clearTimeout(timepath);
            // 间距是 10 * 缩放比例
            let space = 10 * $("html").css("fontSize").replace("px","") /100
            var start = { x: s[0].getBoundingClientRect().left-svgcontainerLeft, y: s[0].getBoundingClientRect().top-svgcontainerTop };
            var m1 = { x: s[0].getBoundingClientRect().left-svgcontainerLeft, y: s[0].getBoundingClientRect().top-svgcontainerTop + space };
            var m2 = { x: e[0].getBoundingClientRect().left-svgcontainerLeft, y: e[0].getBoundingClientRect().top-svgcontainerTop - space };
            var end = { x: e[0].getBoundingClientRect().left-svgcontainerLeft, y: e[0].getBoundingClientRect().top-svgcontainerTop };
            var current = { x: start.x, y: start.y };
            // console.log("linedot", start,m1,m2, end)
            if( start.x == 1189.3646240234375  ){
                console.log(e,tt)
            }
            // 子机构的连接线是黄色,其他是灰色
            let lineColor = e.parent(".tree_sub").length > 0 ? "#DDAF59" : "#B0B4BD";

            //创建直线
            if( m1.x == m2.x && m1.y == m2.y ){
                // start -> end
                var line = document.createElementNS(svgns, "line");
                line.setAttribute("x1", start.x);
                line.setAttribute("y1", start.y);
                line.setAttribute("x2", end.x);
                line.setAttribute("y2", end.y);
                line.setAttribute("stroke", lineColor);
                line.setAttribute("fill", "none");
                svger.appendChild(line);
            }else{
                // start -> m1 -> m2 -> end
                var line1 = document.createElementNS(svgns, "line");
                line1.setAttribute("x1", start.x);
                line1.setAttribute("y1", start.y);
                line1.setAttribute("x2", m1.x);
                line1.setAttribute("y2", m1.y);
                line1.setAttribute("stroke", lineColor);
                line1.setAttribute("fill", "none");
                svger.appendChild(line1);
                var line2 = document.createElementNS(svgns, "line");
                line2.setAttribute("x1", m1.x);
                line2.setAttribute("y1", m1.y);
                line2.setAttribute("x2", m2.x);
                line2.setAttribute("y2", m2.y);
                line2.setAttribute("stroke", lineColor);
                line2.setAttribute("fill", "none");
                svger.appendChild(line2);
                var line3 = document.createElementNS(svgns, "line");
                line3.setAttribute("x1", m2.x);
                line3.setAttribute("y1", m2.y);
                line3.setAttribute("x2", end.x);
                line3.setAttribute("y2", end.y);
                line3.setAttribute("stroke", lineColor);
                line3.setAttribute("fill", "none");
                svger.appendChild(line3);
            }
        }
    }
    // 清除线
    function clearLine(){
        $(".tree_line_dot").remove()
        $("#svgcontainer").html("")
    }

    // 渲染树
    function getTreeHtml(dataArr) {
        let html = '';
        dataArr.map((itm,idx)=>{
            html +=
                `${idx === 0 ? `<div class="tree_layer flexAround ${itm.isTop ? '' : 'tree_layer_line' }">`:''}
                    ${itm.isTop ?
                        `<div class="tree_assembly tree_top">
                            <p class="ellipsis_p" title="${itm.AgencyName}">${itm.AgencyName}</p>
                        </div>
                        `
                        :
                        `<!-- 子机构 -->
                         
                        <div class="tree_layer_line ${idx != 0 && dataArr.length > 1 ? 'ml10':''}">${tree_sub_html(itm,idx,dataArr)}</div>
                            
                        `
                    }
                ${idx === dataArr.length - 1 ? `</div>`:''}
                ${itm.isTop ?
                    `${itm.contactor1 && itm.contactor1.length > 0 ? tree_human_html(itm.contactor1) : ''}
                    ${itm.contactor2 && itm.contactor2.length > 0 ?
                        `<div class="tree_layer flexAround tree_layer_line">
                            ${tree_human_html(itm.contactor2)}
                        </div>` : ''
                    }`
                    :
                    ""
                }
            `;
        })
        function tree_sub_html(itm,idx,dataArr) {
            return `
                <div class="tree_layer flexAround ">
                    <div class="tree_assembly tree_sub">
                        <div class="tree_sub_top tree_edit_item hide_edit">
                            <p class="ellipsis_p tree_sub_name" title="${itm.AgencyName}">${itm.AgencyName}</p>
                            <p class="tree_item_edit"><i class="icon iconguanbi1 tree_item_edit_add"></i><i class="icon_split_line"></i><i class="icon iconshanchu1"></i></p>
                            <p class="tree_triangle"></p>
                            <div class="tree_sub_edit_modal">
                                <p class="tree_triangle"></p>
                                <p class="tree_add_man split">新增人物</p>
                                <p class="tree_add_department">新增部门</p>
                            </div>
                        </div>
                        <div class="tree_sub_msg">
                            <p class="tree_sub_msg_title">
                                <span>规模：</span>
                                <span>2345亿</span>
                                <i class="icon iconzhankaishouqi2 tree_sub_msg_show_detail"></i>
                            </p>
                            <div class="tree_sub_msg_detail">
                                <ul>
                                    <li>
                                        <p>
                                            <span class="tree_dot"></span>
                                            <span class="tree_label">较上季度变化:</span>
                                        </p>
                                        <p class="color_red">
                                            <span class="tree_value">45亿</span>
                                            <i class="icon iconshangjiantou2"></i>
                                        </p>
                                    </li>
                                    <li>
                                        <p>
                                            <span class="tree_dot"></span>
                                            <span class="tree_label">较年初变化:</span>
                                        </p>
                                        <p class="color_red">
                                            <span class="tree_value">115亿</span>
                                            <i class="icon iconshangjiantou2"></i>
                                        </p>
                                    </li>
                                    <li>
                                        <p>
                                            <span class="tree_dot"></span>
                                            <span class="tree_label">较上月变化:</span>
                                        </p>
                                        <p class="color_green">
                                            <span class="tree_value">5亿</span>
                                            <i class="icon iconxiajiantou2"></i>
                                        </p>
                                    </li>
                                    <li>
                                        <p>
                                            <span class="tree_dot"></span>
                                            <span class="tree_label">公募:</span>
                                        </p>
                                        <p class="color_green">
                                            <span class="tree_value">245亿</span>
                                            <i class="icon iconxiajiantou2"></i>
                                        </p>
                                    </li>
                                    <li>
                                        <p>
                                            <span class="tree_dot"></span>
                                            <span class="tree_label">专户:</span>
                                        </p>
                                        <p class="color_red">
                                            <span class="tree_value">23455亿</span>
                                            <i class="icon iconshangjiantou2"></i>
                                        </p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 联系人 -->
                ${itm.contactor1 && itm.contactor1.length > 0 ? tree_human_html(itm.contactor1) : ''}
                ${itm.contactor2 && itm.contactor2.length > 0 ?
                    `<div class="tree_layer flexAround tree_layer_line">
                        ${tree_human_html(itm.contactor2)}
                    </div>` : ''
                }
            `
        }
        function tree_human_html(Contactor) {
            let ContactorHtml = ''
            Contactor.map(itmContactor => {
                // console.log(itmContactor.contactData, itmContactor);
                if( itmContactor.contactData ){   
                    ContactorHtml += `<div class="tree_layer"><div class="tree_layer flexAround ownerContactList">`
                        itmContactor.contactData.forEach(itmContactor2 => {
                            ContactorHtml += `<!-- 联系人 -->
                                <div class="tree_assembly tree_human tree_edit_item hide_edit">
                                    <div class="tree_human_bg">
                                        <p class="tree_human_img"><!-- <img id="aaa" src="D:/AAAWork/assets/images/human.jpg"> --></p>
                                        <p class="tree_human_msg"><span class="tree_human_position">${itmContactor2.position}</span><span class="tree_human_name">${itmContactor2.name}</span></p>
                                        <p class="tree_item_edit"><i class="icon iconguanbi1"></i><i class="icon_split_line"></i><i class="icon iconshanchu1"></i></p>
                                        <p class="tree_human_visitnum">${itmContactor2.visitNum}</p>
                                    </div>
                                    <div class="tree_human_bg overflow_hidden">
                                        <p class="tree_human_bottomborder ${visitColor(itmContactor2.visitNum)}"></p>
                                    </div>
                                </div>
                            `
                        })
                    ContactorHtml += itmContactor.data ? `</div>${getTreeHtml(itmContactor.data)}`:'</div>'
                    ContactorHtml += `</div>`
                }else{
                    ContactorHtml += `
                    <!-- 联系人 -->
                    <div class="tree_layer flexAround">
                        <div class="tree_assembly tree_human tree_edit_item hide_edit">
                            <div class="tree_human_bg">
                                <p class="tree_human_img"><!-- <img id="aaa" src="D:/AAAWork/assets/images/human.jpg"> --></p>
                                <p class="tree_human_msg"><span class="tree_human_position">${itmContactor.position}</span><span class="tree_human_name">${itmContactor.name}</span></p>
                                <p class="tree_item_edit"><i class="icon iconguanbi1"></i><i class="icon_split_line"></i><i class="icon iconshanchu1"></i></p>
                                <p class="tree_human_visitnum">${itmContactor.visitNum}</p>
                            </div>
                            <div class="tree_human_bg overflow_hidden">
                                <p class="tree_human_bottomborder ${visitColor(itmContactor.visitNum)}"></p>
                            </div>
                        </div>
                    </div>
                `}
                
            })
            return ContactorHtml
        }
        function visitColor(visitnum) {
            let colorClass = ''
            if (visitnum >= 0 && visitnum < 10) {
                colorClass = 'bg_red'
            }
            if (visitnum >= 10 && visitnum < 20) {
                colorClass = 'bg_orange'
            }
            if (visitnum >= 20 && visitnum < 30) {
                colorClass = 'bg_yellow'
            }
            if (visitnum >= 30 && visitnum < 40) {
                colorClass = 'bg_blue'
            }
            if (visitnum >= 40) {
                colorClass = 'bg_purple'
            }
            return colorClass;
        }

        return html
    }

    
    // 展开子机构明细
    $(".tree_map").on("click", ".tree_sub_msg_show_detail", function () {
        if ($(this).hasClass("shown")) {
            $(this).removeClass("shown zhankaishouqi_rotate180")
            $(this).parents(".tree_sub_msg").animate({ height: '.22rem' }, 200)
        } else {
            $(this).addClass("shown zhankaishouqi_rotate180")
            $(this).parents(".tree_sub_msg").animate({ height: '1.15rem' }, 200)
        }
        // 画线
        drawLine()
    });

    // hover提示拜访次数
    let t = null
    $("#tree_map").on("mouseenter", ".tree_human_visitnum", function (e) {
        let visitnumHeight = $(this).height()*0.8;//因为font-size是10所以约缩小0.8
        clearTimeout(t);   // 清空定时器
        t=setTimeout(function(){ // 延时操作
            if( $("#visitNumModal").css("display") == "none" ){
                $(".visitNumModal").css({left:e.pageX-($(".visitNumModal").width()/2)+'px',top:e.pageY-$(".visitNumModal").height()-visitnumHeight+'px'});
                $("#visitNumModal").show();
            }
        },300);
     }).on("mouseleave", '.tree_human_visitnum', function(e) { // 鼠标移出事件
        if(t!=null){ // 判断是否显示
          clearTimeout(t);  // 清空定时器
          if( $("#visitNumModal").css("display") !== "none" ){
              $("#visitNumModal").hide();
          }
          t=null;
        }
    });

    // 页面缩放时,重新画线
    $(window).on("resize",function(){
        // 画线
        drawLine()
    })

})